// pages/user-info/user-info.js

import { getMemberById, updateMemberById } from '@/api/member'
import { hideLoading, msg, showLoading, isNull, navBack } from '@/utils/util'
import { uploadFile } from '@/api/file'
import { toIndexPage } from '@/utils/page'

Page({

    data: {
        member: {}, // 会员信息
        tmpAvatarUrl: '', // 临时图片地址
        avatarUrl: '', // 当前会员的头像url
        nickname: '',
        sex: 1,
        birthday: null,
        mobile: '',
        error: {}, // 校验的错误信息对象
    },

    onLoad(options) {
        // console.log('id', options.id)
        this.loadData(options.id)
    },

    // 查询会员详情
    async loadData(id) {
        if (!id) return msg('未传递参数')
        try {
            showLoading()
            const {data: member} = await getMemberById(id)
            const {mobile = '', avatarUrl = '', nickname = '', sex=1, birthday= ''} = member
            this.setData({ member,  mobile, avatarUrl, nickname, sex, birthday })
            // console.log('data', member)
        } catch (error) {
            msg('个人资料获取失败')
            console.error("个人资料获取失败", error)
        } finally {
            hideLoading()
        }
    },

    // 获取选择的头像
    onChooseAvatar(e) {
        const {avatarUrl} = e.detail
        // console.log('onChooseAvatar', avatarUrl)
        this.setData({ tmpAvatarUrl: avatarUrl })
    },

    // 点击保存触发 
    async submitForm(e) {
        try {
            showLoading('保存中')

            // 真机才可以获取成功，模拟器获取不到
            const {nickname} = e.detail.value
            console.log("submitForm", nickname)
            // 1. 校验用户昵称、性别为必填项
            let {member, sex, birthday, avatarUrl, tmpAvatarUrl} = this.data
            let error = {} // 初始为一个空对象
            if (isNull(nickname)) error.nickname = '昵称不能为空'
            if (isNull(sex)) error.sex = '请选择性别'
            this.setData({ error: error })
            // 校验未通过则直接结束
            if (Object.keys(error).length > 0) return
            // 2. 上传头像到云存储
            if (tmpAvatarUrl) {
                console.log('上传头像到云存储')
                const { fileID } = await uploadFile(tmpAvatarUrl, 'avatar')
                console.log('fileId', fileID)
                this.setData({avatarUrl: fileID, tmpAvatarUrl: ''})
                avatarUrl = fileID // 为了保存数据库使用
            }
            // 3. 提交表单数据到数据库中
            const updateData = {avatarUrl, nickname, birthday, sex}
            const { result } = await updateMemberById(member._id, updateData)
            // console.log('result', result)

            // 更新登录用户信息
            getApp().storageMember( {...member, avatarUrl, nickname, birthday, sex} )
            msg('保存成功')
            setTimeout(() => {
                navBack()
            }, 500);
        } catch(error) {
            console.error('保存失败', error)
        } finally {
            hideLoading()
        }
        
    },

    // 退出登录
    logout() {
        wx.removeStorageSync(getApp().memberInfoKey)
        // 退出回到首页
        toIndexPage()
    }

})